<template>
  <div id="userProfileView">
    <h2>个人中心</h2>
    <a-form :model="form" label-align="right" class="user-form">
      <!-- 用户名（修正字段名为userName） -->
      <a-form-item
        field="userName"
        label="用户名"
        label-col="80px"
        wrapper-col="calc(100% - 80px - 8px)"
      >
        <a-input
          v-model="form.userName"
          placeholder="请输入用户名"
          :disabled="!editable"
          class="aligned-input"
        />
      </a-form-item>

      <a-form-item
        field="account"
        label="账号"
        label-col="80px"
        wrapper-col="calc(100% - 80px - 8px)"
      >
        <a-input
          v-model="form.account"
          placeholder="账号"
          disabled
          class="aligned-input"
        />
      </a-form-item>

      <a-form-item
        field="oldPassword"
        label="旧密码"
        label-col="80px"
        wrapper-col="calc(100% - 80px - 8px)"
      >
        <a-input-password
          v-model="form.oldPassword"
          placeholder="请输入旧密码"
          :disabled="!editable"
          class="aligned-input"
        />
      </a-form-item>

      <a-form-item
        field="newPassword"
        label="新密码"
        label-col="80px"
        wrapper-col="calc(100% - 80px - 8px)"
      >
        <a-input-password
          v-model="form.newPassword"
          placeholder="请输入新密码（至少8位）"
          :disabled="!editable"
          class="aligned-input"
        />
      </a-form-item>

      <a-form-item
        field="confirmPassword"
        label="确认新密码"
        label-col="80px"
        wrapper-col="calc(100% - 80px - 8px)"
      >
        <a-input-password
          v-model="form.confirmPassword"
          placeholder="请再次输入新密码"
          :disabled="!editable"
          class="aligned-input"
        />
      </a-form-item>

      <!-- 操作按钮 -->
      <a-form-item label-col="80px" wrapper-col="calc(100% - 80px - 8px)">
        <a-button v-if="!editable" @click="handleEdit" class="start-btn">
          修改信息
        </a-button>
        <a-button
          v-if="!editable"
          @click="handleLogout"
          class="start-btn logout-btn"
        >
          退出登录
        </a-button>
        <a-button
          v-if="editable"
          @click="handleCancel"
          class="start-btn cancel-btn"
        >
          取消
        </a-button>
        <a-button
          v-if="editable"
          @click="handleSubmit"
          class="start-btn submit-btn"
        >
          提交修改
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import { UserControllerService } from "../../../generated";
import message from "@arco-design/web-vue/es/message";
import ACCESS_ENUM from "@/access/accessEnum";

const store = useStore();
const router = useRouter();
const editable = ref(false);

// 表单数据
const form = ref({
  userName: "",
  account: "",
  oldPassword: "",
  newPassword: "",
  confirmPassword: "",
});

// 用户信息
const userInfo = ref({
  id: "",
  userName: "",
  account: "",
});

// 监听用户信息变化，同步到表单
watch(
  () => store.state.user.loginUser,
  (newUser) => {
    userInfo.value = {
      id: newUser.id || "",
      userName: newUser.userName || "",
      account: newUser.account || "",
    };
    form.value.userName = newUser.userName || "";
    form.value.account = newUser.account || "";
  },
  { immediate: true }
);

// 进入编辑模式
const handleEdit = () => {
  editable.value = true;
};

// 取消编辑，重置密码输入框
const handleCancel = () => {
  editable.value = false;
  form.value.oldPassword = "";
  form.value.newPassword = "";
  form.value.confirmPassword = "";
};

// 提交修改（核心逻辑）
const handleSubmit = async () => {
  // 1. 表单验证
  if (!form.value.userName.trim()) {
    message.error("用户名不能为空");
    return;
  }

  // 若修改密码，需验证新旧密码
  if (form.value.newPassword) {
    if (form.value.newPassword.length < 8) {
      message.error("新密码长度不能少于8位");
      return;
    }

    if (form.value.newPassword !== form.value.confirmPassword) {
      message.error("两次输入的新密码不一致");
      return;
    }

    if (!form.value.oldPassword) {
      message.error("修改密码需输入旧密码");
      return;
    }
  }

  try {
    // 2. 构造提交数据（使用个人信息修改接口）
    const updateData = {
      id: userInfo.value.id, // 必须包含用户ID
      userName: form.value.userName,
      oldPassword: form.value.oldPassword,
      newPassword: form.value.newPassword,
    };

    // 3. 调用个人信息修改接口（使用updateMyUserUsingPost代替updateUserUsingPost）
    const res = await UserControllerService.updateMyUserUsingPost(updateData);
    if (res.code === 0 && res.data) {
      message.success("信息更新成功");
      editable.value = false;
      // 清空密码输入框
      form.value.oldPassword = "";
      form.value.newPassword = "";
      form.value.confirmPassword = "";
      // 重新获取用户信息，刷新页面显示
      await store.dispatch("user/getLoginUser");
    } else {
      message.error("更新失败：" + (res.message || "未知错误"));
    }
  } catch (error) {
    console.error("更新失败：", error);
    message.error("网络异常，请重试");
  }
};

// 退出登录
const handleLogout = () => {
  // 清除登录状态
  localStorage.removeItem("token");
  sessionStorage.removeItem("userSession");
  // 更新Vuex状态
  store.commit("user/updateUser", {
    userName: "未登录",
    userRole: ACCESS_ENUM.NOT_LOGIN,
    id: "",
    avatarUrl: "",
    account: "",
  });
  // 跳转登录页
  router.push("/user/login");
  message.success("已退出登录");
};
</script>

<style scoped>
#userProfileView {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.user-form {
  margin-top: 20px;
}

.aligned-input {
  width: 100% !important;
  max-width: 400px;
}

.arco-form-item-label {
  padding-right: 8px !important;
  text-align: right !important;
}

/* 头像样式 */
.avatar-container {
  display: flex;
  align-items: center;
  gap: 16px;
}

.avatar-circle {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  overflow: hidden;
  border: 2px solid #eee;
  flex-shrink: 0;
  background-color: #f5f5f5;
}

.avatar-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: opacity 0.3s;
}

/* 按钮样式 */
.start-btn {
  padding: 0.8rem 2.5rem;
  border-radius: 8px;
  font-size: 1.1rem;
  font-weight: bold;
  transition: all 0.3s;
  margin-right: 16px;
  background-color: white !important;
  color: #2ecc71 !important;
  border: 2px solid #2ecc71 !important;
}

.submit-btn {
  background-color: white !important;
  color: #2ecc71 !important;
  border: 2px solid #2ecc71 !important;
}

.submit-btn:hover {
  background-color: #f8fff8 !important;
}

.cancel-btn {
  background-color: white !important;
  color: #2ecc71 !important;
  border: 2px solid #2ecc71 !important;
}

.cancel-btn:hover {
  background-color: #f9f9f9 !important;
}

.logout-btn {
  background-color: white !important;
  color: #e74c3c !important;
  border: 2px solid #e74c3c !important;
}

.logout-btn:hover {
  background-color: #fff8f8 !important;
}
</style>
